package com.yj.shortLink;

import cn.hutool.bloomfilter.BloomFilterUtil;
import cn.hutool.core.util.HashUtil;
import cn.hutool.core.util.RandomUtil;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 短链工具类
 */
@Component
public class ShortLinkUtil {


    // 线程安全的BloomFilter
    private BloomFilter bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.forName("UTF-8")), 100000000, 0.01);

    // 替换魔数为常量
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int SHORT_LINK_LENGTH = 6;

    // 方法命名修改为更清晰的形式
    public String generateShortLink(String longUrl) {
        String shortLink = generateUniqueShortLink(longUrl, SHORT_LINK_LENGTH);
        if (bloomFilter.mightContain(shortLink)) {
            shortLink = generateUniqueShortLink(longUrl, SHORT_LINK_LENGTH, ThreadLocalRandom.current().nextInt(1, 10));
        }
        bloomFilter.put(shortLink);
        return shortLink;
    }

    private String generateUniqueShortLink(String longUrl, int length) {
        return getShortLink(longUrl, length, null);
    }

    private String generateUniqueShortLink(String longUrl, int length, int random) {
        return getShortLink(longUrl, length, null);
    }

    private static String getShortLink(String longUrl, Integer length, Integer random) {

        long l = random == null ? HashUtil.murmur64((longUrl + "").getBytes(Charset.forName("UTF-8"))) : HashUtil.murmur64((longUrl+random).getBytes(Charset.forName("UTF-8")));
        l = Math.abs(l);
        StringBuilder sb = new StringBuilder();
        for (int i = 6; i > 0; i--) {
            int index = (int) (l % CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
            l = l / CHARACTERS.length();
        }
        return sb.toString();
    }


    public static void main (String[]args){
        String longUrl = "https://www.baidu.com";
        int random = RandomUtil.randomInt(1,5);
        System.out.println("random = " + random);
        String shortUrl = getShortLink(longUrl, SHORT_LINK_LENGTH, random);
        System.out.println("shortUrl = " + shortUrl);
    }
}
